import React, { Component } from 'react';
import {
  View,Text,StyleSheet,TouchableOpacity,Image,ScrollView,Modal,DeviceEventEmitter,
    Platform,
} from 'react-native';
import pxToDp from '../common/comm';
import * as COMM from '../common/comm';
import { StackNavigator } from 'react-navigation';
import Info from './Info';
import ApplyTixian from './ApplyTixian';
import FanliInfo from './FanliInfo';
import TixianInfo from './TixianInfo';
import About from './About';
import ModifyPwd from './ModifyPwd';
import AccountBank from './AccountBank';
import AccountAli from './AccountAli';
import Account from './Account';
import PersonalCenter from './PersonalCenter';
import Login from './Login';
import Register from './Register';
import ResetPassword from './ResetPassword';
import Index from './Index';
import FanliInfoItem from './FanliInfoItem';
import MyIndex from './MyIndex';
import LoginDialog from './LoginDialog';
import RegDialog from './RegDialog';
import ForgetPwd from './ForgetPwd';
import * as DATA from '../data/data';

let time1 = null;
class Mypage extends Component {
  // 构造
    constructor(props) {
      super(props);
      // 初始状态
      this.state = {
        loginkey:null,
        name:'',
        phone:'',
        account:'',
        userInfo:'',
        isModal1:false,
        isModal:false,
        isLoginDialog:false,
        isRegDialog:false,
        isForgetPwdDialog:false,
        isInfo:false,
      };
    }
//提示框3秒后消失µ
  _show(txt) {
    this.setState({
      isModal: true,
      alertTxt: txt
    });
    this.timer = setTimeout(() => {this._hide()},1000);
  }

  _hide() {
    this.setState({
      isModal:false
    })
  }

  isLogin(){
    return this.state.loginkey != null?<TouchableOpacity
        onPress={()=>{
            this.props.navigation.navigate('Info',{userInfo:this.state.userInfo});
            }}
        style={[styles.bg, { justifyContent: 'center', height: pxToDp(150), marginTop: pxToDp(40) }]}>
      <View style={{flexDirection:'row',alignItems:'center',marginLeft:pxToDp(20)}}>
        <View>
          <Text style={[styles.title, { fontSize: pxToDp(26), fontWeight: 'bold' }]}>姓名：{this.state.name}</Text>
          <Text style={[styles.title, { fontSize: pxToDp(26),fontWeight:'bold'}]}>手机号：{this.state.phone}</Text>
          <Text style={[styles.title,{fontSize:pxToDp(26),fontWeight:'bold'}]}>余额：{this.state.account}</Text>
        </View>
        <Image style={[styles.next,{marginLeft:pxToDp(430)}]} source={{uri:DATA.ENTER_IMG}}/>
      </View>
    </TouchableOpacity>:<TouchableOpacity
        onPress={() => {
            this.setState({
              isLoginDialog:true
            });
          }}
        style={[styles.bg,{height:pxToDp(150),marginTop:pxToDp(40)}]}>
      <View style={styles.item}>
        <Image style={styles.userIcon} source={{uri:DATA.ME_IMG}}/>
        <Text style={[styles.title,{fontSize:pxToDp(36)}]}>注册 / 登录</Text>
        <Image style={[styles.next,{marginLeft:pxToDp(230)}]} source={{uri:DATA.ENTER_IMG}}/>
      </View>
    </TouchableOpacity>;
  }

  isShowPwd(){
    return this.state.loginkey != null?
        <TouchableOpacity
            onPress={() => {
              this.props.navigation.navigate('ModifyPwd',{loginkey:this.state.loginkey});
            }}>
          <View style={styles.row}>
            <Image style={styles.itemIcon} source={{uri:DATA.XIUGAIMIMA_IMG}}/>
            <Text style={[styles.title,{fontSize:pxToDp(36)}]}>修改密码</Text>
            <Image style={styles.next} source={{uri:DATA.ENTER_IMG}}/>
          </View>
        </TouchableOpacity>
    :null;
  }

  isShowLogout(){
    return this.state.loginkey != null?<TouchableOpacity
        onPress={() => {
            this._show('退出登录');
            this.setState({
              loginkey:null
            });
            DeviceEventEmitter.emit('logout',this.state.loginkey);
            DeviceEventEmitter.emit('logout2',this.state.loginkey);
          }}>
      <View style={[styles.row,{marginTop:pxToDp(5)}]}>
        <Image style={styles.itemIcon} source={{uri:DATA.TUICHUDENGLU_IMG}}/>
        <Text style={[styles.title,{fontSize:pxToDp(36)}]}>退出登录</Text>
        <Image style={styles.next} source={{uri:DATA.ENTER_IMG}}/>
      </View>
    </TouchableOpacity>:null;
  }

  componentWillMount(){
  }

  componentWillUnMount() {
    DeviceEventEmitter.remove();
  }

  componentDidMount(){
    DeviceEventEmitter.addListener('product', (info)=>{
      this.setState({
        name:info.nickname,
        phone:info.loginname,
        account:info.account,
        loginkey:info.loginkey,
        userInfo:info
      })
    });

      DeviceEventEmitter.addListener('changeAccount', (info)=>{
          this.setState({
              account:info,
          })
      });
  };
  //判断渠道是否完善
  isHasAccount(){
    let _that = this;
    let data2 = 'loginkey='+this.state.loginkey;
    fetch(DATA.ACCOUNT_URL,{
      method: "POST",
      headers:{'Content-Type': 'application/x-www-form-urlencoded' },
      body: data2
    })
        .then((response) => {       // 数据解析方式
          if (response.ok) {
            return response.json();
          }
        })
        .then((responseData) => {       // 获取到的数据处理
          if(responseData.status == 1){
            if(responseData.zfb !== null || responseData.yhk !== null){
              _that.props.navigation.navigate('ApplyTixian',{userInfo:_that.state.userInfo});
            }else{
              _that.setState({isModal1:true})
            }
          }
        })
        .catch((error) => { // 错误处理
          alert('Mypage获取数据失败，请重试！');
        })
        .done();
  }

  change(isLogin,isReg,isForget,userInfo){
    if(userInfo){
      this.setState({
        name:userInfo.nickname,
        phone:userInfo.loginname,
        account:userInfo.account,
        userInfo:userInfo,
        loginkey:userInfo.loginkey
      });
    }
    this.setState({
      isLoginDialog:isLogin,
      isRegDialog:isReg,
      isForgetPwdDialog:isForget,
    })
  }

  render() {
    return (
      <ScrollView style={styles.container}>
        {/*完善信息框*/}
        <Modal
            animationType='fade'            // 淡入淡出
            transparent={true}              // 透明
            visible={this.state.isModal1}    // 根据isModal决定是否显示
            onRequestClose={() => {this.onRequestClose()}}  // android必须实现
        >
          <View style={modalStyle1.modalViewStyle}>
            <View style={modalStyle1.hudViewStyle}>
              <View style={modalStyle1.container}>
                <View style={modalStyle1.containerItem}>
                  <Text style={modalStyle1.txt}>由于您返利账户尚未完善！</Text>
                  <Text style={modalStyle1.txt}>请完善后，进行提现操作！</Text>
                </View>
                <View style={modalStyle1.containerBtn}>
                  <Text
                      style={modalStyle1.btn}
                      onPress={()=>{this.setState({isModal1:false})}}
                  >稍后</Text>
                  <Text
                      style={[modalStyle1.btn,{color:'red'}]}
                      onPress={()=>{
                      this.props.navigation.navigate('Account',{userInfo:this.state.userInfo,isHasAccount:this.state.isModal});
                      this.setState({isModal1:false})
                      }}
                  >现在去</Text>
                </View>
              </View>
            </View>
          </View>
        </Modal>
        {/*提示框*/}
        <Modal
            animationType='fade'            // 淡入淡出
            transparent={true}              // 透明
            visible={this.state.isModal}    // 根据isModal决定是否显示
            onRequestClose={() => {this.onRequestClose()}}  // android必须实现
        >
          <View style={modalStyle.modalViewStyle}>
            <View style={modalStyle.hudViewStyle}>
              <Text style={modalStyle.hudTextStyle}>{this.state.alertTxt}</Text>
            </View>
          </View>
        </Modal>
        {/*登录框*/}
        <Modal
            animationType='fade'            // 淡入淡出
            transparent={true}              // 透明
            visible={this.state.isLoginDialog}    // 根据isModal决定是否显示
            onRequestClose={() => {this.onRequestClose()}}  // android必须实现
        >
          <View style={login.modalViewStyle}>
            <LoginDialog
                isClose={this.state.isLoginDialog}
                change = {this.change.bind(this)}
            />
          </View>
        </Modal>
        {/*注册框*/}
        <Modal
            animationType='fade'            // 淡入淡出
            transparent={true}              // 透明
            visible={this.state.isRegDialog}    // 根据isModal决定是否显示
            onRequestClose={() => {this.onRequestClose()}}  // android必须实现
        >
          <View style={login.modalViewStyle}>
            <RegDialog
                isClose={this.state.isRegDialog}
                change = {this.change.bind(this)}
            />
          </View>
        </Modal>
        {/*忘记密码框*/}
        <Modal
            animationType='fade'            // 淡入淡出
            transparent={true}              // 透明
            visible={this.state.isForgetPwdDialog}    // 根据isModal决定是否显示
            onRequestClose={() => {this.onRequestClose()}}  // android必须实现
        >
          <View style={login.modalViewStyle}>
            <ForgetPwd
                isClose={this.state.isForgetPweDialog}
                change = {this.change.bind(this)}
            />
          </View>
        </Modal>
        {this.isLogin()}
        {/*申请提现*/}
        <TouchableOpacity
          onPress={() => {
              if(this.state.loginkey === null){
                this._show('请登录')
              } else {
                this.isHasAccount();
              }
            }}>
          <View style={styles.row}>
            <Image style={styles.itemIcon} source={{uri:DATA.SHENQINGTIXIAN_IMG}}/>
            <Text style={[styles.title,{fontSize:pxToDp(36)}]}>申请提现</Text>
            <Image style={styles.next} source={{uri:DATA.ENTER_IMG}}/>
          </View>
        </TouchableOpacity>
        {/*返利记录*/}
        <TouchableOpacity
          onPress={() => {
            if(this.state.loginkey === null){
              this._show('请登录')
            }else{
              this.props.navigation.navigate('FanliInfo',{loginkey:this.state.loginkey});
            }
          }}>
          <View style={styles.row}>
            <Image style={styles.itemIcon} source={{uri:DATA.FANLIJILU_IMG}}/>
            <Text style={[styles.title,{fontSize:pxToDp(36)}]}>返利记录</Text>
            <Image style={styles.next} source={{uri:DATA.ENTER_IMG}}/>
          </View>
        </TouchableOpacity>
        {/*提现记录*/}
        <TouchableOpacity
          onPress={() => {
            if(this.state.loginkey === null){
              this._show('请登录')
            }else{
              this.props.navigation.navigate('TixianInfo',{loginkey:this.state.loginkey});
            }
          }}>
          <View style={[styles.row,{marginTop:pxToDp(5)}]}>
            <Image style={styles.itemIcon} source={{uri:DATA.TIXIANJILU_IMG}}/>
            <Text style={[styles.title,{fontSize:pxToDp(36)}]}>提现记录</Text>
            <Image style={styles.next} source={{uri:DATA.ENTER_IMG}}/>
          </View>
        </TouchableOpacity>
        {/*关于伏蒙*/}
        <TouchableOpacity
          onPress={() => {
              this.props.navigation.navigate('About');
          }}>
          <View style={styles.row}>
            <Image style={styles.itemIcon} source={{uri:DATA.GUANYUFUMENG_IMG}}/>
            <Text style={[styles.title,{fontSize:pxToDp(36)}]}>关于伏蒙</Text>
            <Image style={styles.next} source={{uri:DATA.ENTER_IMG}}/>
          </View>
        </TouchableOpacity>
        {this.isShowPwd()}
        {this.isShowLogout()}
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    backgroundColor:'transparent',
    height:pxToDp(1400)
  },
  bg: {
    backgroundColor: '#fff',
  },
  item: {
    flexDirection: 'row',
    paddingTop: pxToDp(15),
    paddingLeft:pxToDp(30),
    alignItems:'center'
  },
  userIcon: {
    width: pxToDp(120),
    height:pxToDp(120)
  },
  next: {
    width: pxToDp(40),
    height: pxToDp(40),
    position:'absolute',
    right:pxToDp(30)
  },
  title: {
    marginLeft:pxToDp(30)
  },
  itemIcon:{
    width:pxToDp(50),
    height:pxToDp(50)
  },
  row:{
    flexDirection:'row',
    alignItems:'center',
    backgroundColor:'#fff',
    height:pxToDp(80),
    marginTop:pxToDp(40),
    paddingLeft:pxToDp(50)
  }
});

export default My = StackNavigator({
  Mypage:{
    screen: Mypage,
    navigationOptions :{
    headerTintColor:'#fff',
    headerTitle: '我的',
    headerStyle: {
      backgroundColor: DATA.BASE_COLOR,
        height:Platform.OS === 'android'?pxToDp(84):pxToDp(110)
    },
    headerTitleStyle: {
      color: '#fff',
      fontSize: pxToDp(34),
        marginLeft:Platform.OS === 'android'?pxToDp(280):null
    },
    gesturesEnabled :true
    }
  },
  Info: {
    screen: Info,
    navigationOptions: {
      headerTintColor:'#fff',
      headerTitle: '个人中心',
      headerStyle: {
        backgroundColor: DATA.BASE_COLOR,
          height:Platform.OS === 'android'?pxToDp(84):pxToDp(110)
      },
      headerTitleStyle: {
        color: '#fff',
        fontSize: pxToDp(34),
          marginLeft:Platform.OS === 'android'?pxToDp(185):null
      },
      gesturesEnabled :true
    }
  },
  ApplyTixian: {
    screen: ApplyTixian,
  },
  FanliInfo: {
    screen: FanliInfo,
  },
  TixianInfo: {
    screen: TixianInfo,
  },
  About: {
    screen: About,
  },
  ModifyPwd: {
    screen: ModifyPwd,
  },
  AccountBank: {
    screen:AccountBank
  },
  Account:{
    screen:Account
  },
  AccountAli:{
    screen:AccountAli
  },
  PersonalCenter: {
    screen:PersonalCenter
  },
  Login: {
    screen:Login
  },
  Register: {
    screen:Register
  },
  ResetPassword: {
    screen:ResetPassword
  },
  MyIndex:{
    screen:MyIndex
  },
  FanliInfoItem:{
    screen:FanliInfoItem
  }
});

const modalStyle1 = StyleSheet.create({
  modalViewStyle: {
    position: 'absolute',
    alignSelf:'center',
  },
  hudViewStyle: {
    backgroundColor: 'rgba(0,0,0,0.5)',
    width:pxToDp(640),
    height:pxToDp(1150),
    justifyContent:'center',
    alignItems:'center'
  },
  container:{
    width:pxToDp(420),
    height:pxToDp(230),
    backgroundColor:'#fff'
  },
  containerItem:{
    height:pxToDp(150),
    backgroundColor:'#000',
    justifyContent:'center',
    alignItems:'center'
  },
  containerBtn:{
    flexDirection:'row'
  },
  txt:{
    color:'#fff',
    fontSize:pxToDp(28)
  },
  btn:{
    flex:1,
    height:pxToDp(80),
    textAlign:'center',
    textAlignVertical:'center',
    fontSize:pxToDp(26)
  }
});

const modalStyle = StyleSheet.create({
  modalViewStyle: {
    position: 'absolute',
    top:pxToDp(900),
    alignSelf:'center'
  },
  hudViewStyle: {
    backgroundColor: 'rgba(0,0,0,0.5)',
    paddingLeft:pxToDp(15),
    paddingRight:pxToDp(15),
    paddingTop:pxToDp(10),
    paddingBottom: pxToDp(10),
    borderRadius:pxToDp(10)
  },
  hudTextStyle: {
    color:'#fff'
  }
});

const login = StyleSheet.create({
  modalViewStyle: {
  },
  hudViewStyle: {
  },
  hudTextStyle: {
  }
});